﻿using System;
using System.Collections.Generic;
using System.Dynamic;

namespace _141_在自定义动态类型中直接定义成员_动态类型
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic dddd = new 我的自定义类();

            dddd.WorkName = "冲压工序";
            dddd.WorkDescription = "此工序需要持续较长时间";
            dddd.IsStartd = false;
            dddd.WorkType = 15;
            dddd.StartTime = new DateTime(2018, 8, 3);


            Console.WriteLine($"Work Name:{dddd.WorkName}");
            Console.WriteLine($"Work Name:{dddd.WorkDescription}");
            Console.WriteLine($"Work Name:{dddd.IsStartd}");
            Console.WriteLine($"Work Name:{dddd.StartTime}");

        }
    }

    //从DynamicObject类派生出一个自定义的动态类型
    public class 我的自定义类 : DynamicObject
    {
        private IDictionary<string, object> 数据 = new Dictionary<string, object>();

        //明确定义的属性，动态类型会直接访问该属性
        public string WorkDescription { get; set; }
        public string WorkName { get; set; }
        public bool IsStarted { get; set; }

        //其它未声明的属性就通过重写TryGetMember和TrySetMember方法访问
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            Console.WriteLine($"\n类中未定义的成员：{binder.Name}\n");
            return 数据.TryGetValue(binder.Name.ToLower(), out result);
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            return 数据.TryAdd(binder.Name.ToLower(), value);
        }

    }

}
